package geektime.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Date;

/**
 * @description: MultiThreadReactorClient
 * @author: general
 * @version: 1.0
 * @create: 2022-05-04 16:11
 **/
public class MultiThreadReactorClient {
    
    private  SocketChannel socketChannel;

    private  ByteBuffer buffer;



    public  void stop() throws IOException {
        socketChannel.close();
        buffer = null;
    }

    private MultiThreadReactorClient() {
        try {
            socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 1234));
            buffer = ByteBuffer.allocate(256);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        for(int i=0; i<100; i++){
            MultiThreadReactorClient client = new MultiThreadReactorClient();
            client.sendMessage("hello"+i);
        }
    }


    public String sendMessage(String msg) {
        buffer = ByteBuffer.wrap(msg.getBytes());
        String response = null;
        try {
            socketChannel.write(buffer);
            buffer.clear();
            buffer = ByteBuffer.allocate(256);
            socketChannel.read(buffer);
            response = new String(buffer.array()).trim();
            System.out.println("response=" + response + " date is "+ new Date());
            buffer.clear();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;

    }
}
